<?php		
	session_start();
	
	/**
	 * 在你运行本demo之前请到 http://connect.opensns.qq.com/申请appid, appkey, 并注册callback地址
	 */
	//申请到的appid
	//$_SESSION["appid"]    = yourappid; 
	$_SESSION["appid"]    = 100297168; 
	
	//申请到的appkey
	//$_SESSION["appkey"]   = "yourappkey"; 
	$_SESSION["appkey"]   = "b8cee8a4a93d5f2ba8822b8d2a96b321"; 
	
	//QQ登录成功后跳转的地址,请确保地址真实可用，否则会导致登录失败。
	//$_SESSION["callback"] = "http://your domain/oauth/get_access_token.php"; 
	$_SESSION["callback"] = url("?module=connect&file=qzone&action=callback");
	
	//QQ授权api接口.按需调用
	$_SESSION["scope"] = "get_user_info,add_share,list_album,add_album,upload_pic,add_topic,add_one_blog,add_weibo";
	
	//print_r ($_SESSION);
	
	
	
	switch($action){
	
		/*登录&授权*/
		case 'authorize':
			
			$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
			$login_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=" 
				. $_SESSION["appid"] . "&redirect_uri=" . urlencode($_SESSION["callback"])
				. "&state=" . $_SESSION['state']
				. "&scope=".$_SESSION["scope"];
			header("Location:$login_url");
		
		break;
		
		/*返回*/
		case 'callback':
			
			//debug
			//print_r($_REQUEST);
			//print_r($_SESSION);
		
			/*安全性检查*/
			/*if($_REQUEST['state'] == $_SESSION['state']) //csrf
			{*/
				$token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
					. "client_id=" . $_SESSION["appid"]. "&redirect_uri=" . urlencode($_SESSION["callback"])
					. "&client_secret=" . $_SESSION["appkey"]. "&code=" . $_REQUEST["code"];
		
				$response = get_url_contents($token_url);
				if (strpos($response, "callback") !== false)
				{
					$lpos = strpos($response, "(");
					$rpos = strrpos($response, ")");
					$response  = substr($response, $lpos + 1, $rpos - $lpos -1);
					$msg = json_decode($response);
					if (isset($msg->error))
					{
						echo "<h3>error:</h3>" . $msg->error;
						echo "<h3>msg  :</h3>" . $msg->error_description;
						exit;
					}
				}
		
				$params = array();
				parse_str($response, $params);
		
				//debug
				//print_r($params);
		
				//set access token to session
				$_SESSION["access_token"] = $params["access_token"];
				
				// 获取OPENID
				$graph_url = "https://graph.qq.com/oauth2.0/me?access_token=" 
				. $_SESSION['access_token'];
		
				$str  = get_url_contents($graph_url);
				if (strpos($str, "callback") !== false)
				{
					$lpos = strpos($str, "(");
					$rpos = strrpos($str, ")");
					$str  = substr($str, $lpos + 1, $rpos - $lpos -1);
				}
			
				$user = json_decode($str);
				if (isset($user->error))
				{
					echo "<h3>error:</h3>" . $user->error;
					echo "<h3>msg  :</h3>" . $user->error_description;
					exit;
				}
			
				//debug
				//echo("Hello " . $user->openid);
				
				
			
				//set openid to session
				$_SESSION["openid"] = $user->openid;
				
				
				/*获取用户资料*/
				$graph_url = "https://graph.qq.com/user/get_user_info?access_token=".$_SESSION["access_token"]."&oauth_consumer_key=".$_SESSION["appid"]."&openid=".$_SESSION["openid"]."&format=json";
				
				$str  = get_url_contents($graph_url);
			
				if($str!==FALSE){
					$result = json_decode($str,true);
					
					// 返回码，0为正确
					if($result["ret"]==0){
						/*echo "<tr><td class='narrow-label'>用户昵称:</td><td>".$result["nickname"]."</td></tr>";
						echo "<tr><td class='narrow-label'>小等头像:</td><td><img src='".$result["figureurl"]."' border='0' /></td></tr>";
						echo "<tr><td class='narrow-label'>中等头像:</td><td><img src='".$result["figureurl_1"]."' border='0' /></td></tr>";
						echo "<tr><td class='narrow-label'>大等头像:</td><td><img src='".$result["figureurl_2"]."' border='0' /></td></tr>";
						echo "<tr><td class='narrow-label'>用户性别:</td><td>".$result["gender"]."</td></tr>";
						echo "<tr><td class='narrow-label'>用户黄钻:</td><td>".$result["vip"]."</td></tr>";
						echo "<tr><td class='narrow-label'>黄钻等级:</td><td>".$result["level"]."</td></tr>";*/
						
						$memberinfo = $db->get_one("select `userid`,`username`,`password`,`email`,`modelid`,`avatar`,`openid`,`nickname` from ".DB_PRE."member where `openid` = '".$_SESSION["openid"]."'");
						
						$userid = $memberinfo['userid'];
						$md5_password = $memberinfo['password'];
						
						if(!$memberinfo){
							/*注册*/
							$memberinfo['username'] = 'temp_'.time();
							$memberinfo['password'] = '123456';
							$memberinfo['email'] = 'sss@qq.com';
							$memberinfo['gender'] = $result["gender"] == '男' ? 0 : 1;
							$memberinfo['modelid'] = '10';
							$memberinfo['avatar'] = $result["figureurl_2"];
							$memberinfo['openid'] = $_SESSION["openid"];
							$memberinfo['nickname'] = $result["nickname"];
							
							/*加载语言包*/
							require_once MOD_ROOT.'member/member.lang.php';
							require_once MOD_ROOT.'member/member_admin.lang.php';
			
							if(!$userid)
							{
								$userid = $member->register($memberinfo);
							}
							if(!$userid) showmessage($member->msg(), SITE_URL);
							
							$md5_password = $member->password($memberinfo['password']);
							
						}
						
						$site_auth_key = md5(AUTH_KEY.$_SERVER['HTTP_USER_AGENT']);
						$site_auth = site_auth($userid."\t".$md5_password, 'ENCODE', $site_auth_key);
						
						//$site_auth = base64_encode($userid."\t".$md5_password);
						set_cookie('auth', $site_auth, time()+3600*24*7);// 设置一个7天过期的COOKIE
						
						
							
							
						$script = "<script language='javascript'>";
						$script .= "window.opener.location.reload();";
						$script .= "window.close(); ";
						$script .= "</script>";
					
									
						showmessage('登录成功！'.$script, SITE_URL);
						
						
					}else{
						echo "<tr><td class='narrow-label'>反馈消息:</td><td>".$result["msg"]."</td></tr>";
					}
				}else{
					echo "<tr><td class='narrow-label'>反馈消息:</td><td>获取用户信息失败。</td></tr>";
				}
		
			/*}
			else 
			{
				echo("The state does not match. You may be a victim of CSRF.");
			}*/
			
		break;	
		
		case 'debug':
			var_dump($_SESSION);
		break;
		
		case 'get_user_info':
			 
		break;
		
		case 'logout':
			
			unset($_SESSION['appid'],$_SESSION["appkey"],$_SESSION["openid"]);
			header("Location: ./index.php?profile=qq_login");
		break; 
		 
	} 
	
	
	
	
	/*常用方法*/
	function do_post($url, $data)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
		curl_setopt($ch, CURLOPT_POST, TRUE); 
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
		curl_setopt($ch, CURLOPT_URL, $url);
		$ret = curl_exec($ch);
	
		curl_close($ch);
		return $ret;
	}
	
	function get_url_contents($url)
	{
		/*if (ini_get("allow_url_fopen") == "1")
		
			return file_get_contents($url);*/
	
		/*$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_URL, $url);
		$result =  curl_exec($ch);
		curl_close($ch);
	
		return $result;*/
		
		$ch = curl_init();
		if(stripos($url,"https://")!==FALSE){
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		}
	
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
		$result = curl_exec($ch);
		$status = curl_getinfo($ch);
		curl_close($ch);
		
		if(intval($status["http_code"])==200){
			return $result;
		}else{
			echo "返回出错:<pre>".$status["http_code"].",请检查参数或者确实是腾讯服务器出错咯。</pre>";
			return false;
		}
	}
	
	
?>
<a href="./index.php?profile=qq_login&action=login">QQ登录</a>